import React, { useEffect, useState } from 'react';
import { ScrollView, StyleSheet, Text, View } from 'react-native'
import { DragSortableView } from 'react-native-drag-sort';
import { RootState } from '@/models/index';
import { ICategory } from '@/models/category'
import { connect, ConnectedProps } from 'react-redux';
import { RootStackNavigation } from '@/navigator/index';
import Item, { parentWidth, itemWidth, itemHeight, margin } from './Item';
import HeaderRightBtn from './HeaderRightBtn'
import _ from 'lodash'
import Touchable from '@/components/Touchable';

const mapStateToProps = ({ category }: RootState) => {
    return {
        myCategorys: category.myCategorys,
        categorys: category.categorys,
        isEdit: category.isEdit,
    };
};

const connector = connect(mapStateToProps);

type ModelState = ConnectedProps<typeof connector>;

interface IProps extends ModelState {
    navigation: RootStackNavigation;
}

const fixedItems = [0, 1];

function Category(props: IProps) {
    const { isEdit, categorys, dispatch, navigation } = props;
    const [myCategorys, setMyCategorys] = useState(props.myCategorys);
    const [scrollEnabled, setScrollEnabled] = useState(true);
    const clasifyGroup = _.groupBy(categorys, item => item.classify);

    const onSubmit = () => {
        dispatch({
            type: 'category/toggle',
            payload: {
                myCategorys,
            },
        });
        console.log(isEdit)
        if (isEdit) {
            navigation.goBack();
        }
    }
    useEffect(() => {
        props.navigation.setOptions({
            headerRight: () => <HeaderRightBtn onSubmit={onSubmit} />,
        });
        return () => {
            console.log('unmount')
            dispatch({
                type: 'category/setState',
                payload: {
                    isEdit: false,
                },
            });
        }
    }, [])


    const onPress = (item: ICategory, index: number, selected: boolean) => {
        const disabled = fixedItems.indexOf(index) > -1;
        if (disabled) return;
        if (isEdit) {
            if (selected) {
                setMyCategorys(myCategorys.filter(
                    selectedItem => selectedItem.id !== item.id,
                ))
            } else {
                setMyCategorys(myCategorys.concat([item]))
            }
        }
    };

    const onClickItem = (data: ICategory[], item: ICategory) => {
        onPress(item, data.indexOf(item), true);
    };

    const renderItem = (item: ICategory, index: number) => {

        const disabled = fixedItems.indexOf(index) > -1;
        return (
            <Item
                key={item.id}
                data={item}
                disabled={disabled}
                isEdit={isEdit}
                selected
            />
        );
    };

    const onLongPress = () => {
        dispatch({
            type: 'category/setState',
            payload: {
                isEdit: true,
            },
        });
    };
    const renderUnSelectedItem = (item: ICategory, index: number) => {
        const { isEdit } = props;
        return (
            <Touchable
                key={item.id}
                onPress={() => onPress(item, index, false)}
                onLongPress={onLongPress}
            >
                <Item data={item} isEdit={isEdit} selected={false} />
            </Touchable>
        );
    };

    const onDataChange = (data: ICategory[]) => {
        setMyCategorys(data)

    };
    return (
        <ScrollView style={styles.container} scrollEnabled={scrollEnabled}>
            <Text style={styles.classifyName}>我的分类</Text>
            <View style={styles.classifyView}>
                <DragSortableView
                    sortable={isEdit}
                    keyExtractor={item => item.id}
                    dataSource={myCategorys}
                    renderItem={renderItem}
                    fixedItems={fixedItems}
                    parentWidth={parentWidth}
                    childrenWidth={itemWidth}
                    childrenHeight={itemHeight}
                    marginChildrenTop={margin}
                    onClickItem={onClickItem}
                    onDataChange={onDataChange}
                    onDragStart={() => {
                        setScrollEnabled(false)
                    }}
                    onDragEnd={() => {
                        setScrollEnabled(true)
                    }}
                >

                </DragSortableView>
            </View>
            <View>
                {Object.keys(clasifyGroup).map(classify => {
                    return (
                        <View key={classify}>
                            <Text style={styles.classifyName}>{classify}</Text>
                            <View style={styles.classifyView}>
                                {clasifyGroup[classify].map((item, index) => {
                                    if (
                                        myCategorys.find(
                                            selectedItem => selectedItem.id === item.id,
                                        )
                                    ) {
                                        return null;
                                    }
                                    return renderUnSelectedItem(item, index);
                                })}
                            </View>
                        </View>
                    );
                })}
            </View>
        </ScrollView>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f3f6f6',
    },
    classifyName: {
        fontSize: 16,
        marginTop: 14,
        marginBottom: 8,
        marginLeft: 10,
    },
    classifyView: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        padding: 5,
    },
});

export default connector(Category)